/* eslint-disable react-hooks/rules-of-hooks */
import {
  ModalForm,
  PageContainer,
  ProCard,
  ProFormText,
  ProFormTextArea,
  QueryFilter,
} from '@ant-design/pro-components';

import { useDispatch, useSelector } from '@umijs/max';
import { Button, Flex, Form, Table, message } from 'antd';
import { useEffect, useState } from 'react';
import { table } from './_table';

const projectBaseInfoPage = () => {
  const dispatch = useDispatch();

  const { list, currentPage, pageSize, total } = useSelector(
    (state) => state.projectBaseInfo,
  );

  const { refresh } = useSelector((state) => state.global);
  const loading = useSelector((state) => state.loading);

  const [modalVisit, setModalVisit] = useState(false);

  const [formRef] = Form.useForm();

  const [id, setId] = useState(null);

  const [messageApi, contextHolder] = message.useMessage();

  const [rowKeys,setRowKeys] = useState(null)

  // 编辑
  const editModal = (data) => {
    setId(data.id);
    formRef?.setFieldsValue(data);
    setModalVisit(true);
  };

  // 新增
  const addModal = () => {
    setId(null);
    formRef?.resetFields();
    setModalVisit(true);
  };

  useEffect(() => {
    initData();
  }, [refresh]);

  // 初始化
  const initData = () => {
    dispatch({
      type: 'projectBaseInfo/pageProjectBaseInfo',
      payload: {
        currentPage,
        pageSize,
      },
    });
  };

  const handleOnChange = (currentPage, pageSize) => {
    dispatch({
      type: 'projectBaseInfo/pageProjectBaseInfo',
      payload: {
        currentPage,
        pageSize,
      },
    });
  };

  const handleOnShowSizeChange = () => {
    dispatch({
      type: 'projectBaseInfo/pageProjectBaseInfo',
      payload: {
        list: [],
      },
    });
  };

  const handleOnFinish = (values) => {
    dispatch({
      type: 'projectBaseInfo/pageProjectBaseInfo',
      payload: {
        ...values,
      },
    });
  };

  const handleSave = (values) => {
    dispatch({
      type: 'projectBaseInfo/saveProjectBaseInfo',
      payload: {
        ...values,
      },
    });
  };

  const rowSelection = {
    onChange: (rowKeys) => {
      setRowKeys(rowKeys)
      console.log(`selectedRowKeys: ${rowKeys}`);
    },
  };

  const handleDelete = () => {
     dispatch({
      type: 'projectBaseInfo/deleteProjectBaseInfo',
      payload: {
        ids: rowKeys !== null?rowKeys.join(','):null
      }
     })
  }

  return (
    <PageContainer>
      {contextHolder}
      <ProCard>
        <QueryFilter defaultCollapsed split onFinish={handleOnFinish}>
          <ProFormText name="name" label="项目名称" />
        </QueryFilter>
        <Flex gap="small" wrap="wrap" style={{marginBottom: 10}}>
          <Button type="primary" onClick={() => addModal()}>
            新增
          </Button>
          <Button type="primary" danger onClick={()=>handleDelete()}>删除</Button>
        </Flex>

        <Table
          loading={loading.effects['projectBaseInfo/pageProjectBaseInfo']}
          columns={table(editModal)}
          dataSource={list}
          rowKey={(row) => row.id}
          pagination={{
            total,
            showLessItems: true,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
            onChange: handleOnChange,
            onShowSizeChange: handleOnShowSizeChange,
          }}
          rowSelection={{
            ...rowSelection,
          }}
        />

        <ModalForm
          title={id !== null ? '编辑' : '新增'}
          form={formRef}
          open={modalVisit}
          onFinish={(values) => {
            if (id !== null) {
              values.id = id;
            }
            handleSave(values);
            return true;
          }}
          onOpenChange={setModalVisit}
          layout="horizontal"
        >
          <ProFormText
            name="name"
            label="项目名称"
            placeholder="请输入项目名称"
            rules={[{ required: true, message: '请输入项目名称' }]}
          />
          <ProFormTextArea
            name="description"
            label="项目描述"
            placeholder="请输入项目描述"
          />
          <ProFormText
            name="prodUrl"
            label="正式环境"
            placeholder="请输入正式环境"
          />
          <ProFormText
            name="testUrl"
            label="测试环境"
            placeholder="请输入测试环境"
          />
          <ProFormText
            name="devUrl"
            label="开发环境"
            placeholder="请输入开发环境"
          />
        </ModalForm>
      </ProCard>
    </PageContainer>
  );
};

export default projectBaseInfoPage;
